// 存储服务
var AV = require('leancloud-storage');
var {
    Query,
    User
} = AV;
AV.init('jAj1l0U2DG2FUiRUEgREnt9C-gzGzoHsz', 'KIcQ4lmqTVNiuAhy0sOEn4M4');


const queryTest = () => {
    var query = new AV.Query('AppVersion');
    query.find().then(function (todo) {
        // 成功获得实例
        // todo 就是 id 为 57328ca079bc44005c2472d0 的 Todo 对象实例
        console.log(todo)
    }, function (error) {
        // 异常处理
        console.log(error)
    });
}

const queryAll = (className) => {
    return new Promise((reslove, reject) => {
        new Query(className).find().then((res) => {
            reslove(res);
        }, (err) => {
            reject(err);
        })
    })

}

/**
 * 分页查询
 * @param {*} option
 * @param {*} pageOption
 * @param {*} className
 */
const queryOptionPage = (option, pageOption = {
    pageSize,
    pageIndex
}, className) => {
    return new Promise((reslove, reject) => {
        let query = new Query(className);
        pageOption.pageSize = pageOption && pageOption.pageSize <= 100 ? pageOption.pageSize : 10;
        pageOption.pageIndex = pageOption && pageOption.pageIndex >= 0 ? pageOption.pageIndex : 0;
        query.limit(pageOption.pageSize);
        query.skip(pageOption.pageSize * pageOption.pageIndex);

        if (option) {
            for (var key in option) {
                query.equalTo(key, option[key]);
            }
        }

        if (pageOption.order && pageOption.sort) {
            if (pageOption.order == 'DESC') {
                query.descending(pageOption.sort)
            } else if (pageOption.order == 'ASCE') {
                query.ascending(pageOption.sort)
            }
        } else {
            query.descending('updatedAt');
        }
        query.find().then((res) => {
            reslove(res);
        }, (err) => {
            reject(err);
        })
    })
}

/**
 * 查询更新信息，返回一个最新可用更新版本
 * @param {*} fromVersionName
 * @param {*} fromVersionCode
 * @param {*} AppType
 * @param {*} BuildType
 */
const queryVersion = (fromVersionName, fromVersionCode, AppType, BuildType) => {
    return new Promise((reslove, reject) => {
        (async () => {
            const queryTasks = [];
            if (fromVersionCode && fromVersionName) {
                var query = new AV.Query('Version');
                query.equalTo('FromVersionName', fromVersionName);
                query.equalTo('FromVersionCode', fromVersionCode);
                query.equalTo('AppType', AppType);
                query.equalTo('BuildType', BuildType);
                query.addDescending('VersionName');
                query.limit(1);
                queryTasks.push(query.find());
            }
            var query1 = new AV.Query('Version');
            query1.equalTo('IsForce', false);
            query1.equalTo('IsPatch', false);
            query1.equalTo('AppType', AppType);
            query1.equalTo('BuildType', BuildType);
            query1.addDescending('VersionName');
            query1.limit(1);
            queryTasks.push(query1.find());
            const resp = await Promise.all(queryTasks);
            let latest = null;
            let forceUpdate = null;
            resp.forEach(d => {
                d.forEach(d1 => {
                    if (d1.get('IsForce')) {
                        forceUpdate = d1;
                    }
                    if (!latest || latest.get('VersionName') < d1.get('VersionName')) {
                        latest = d1;
                    }
                })
            })
            if (forceUpdate) {
                reslove(forceUpdate);
            } else {
                reslove(latest);
            }
        })();
    })
}

const queryOption = (option, className) => {
    return new Promise((reslove, reject) => {
        var query = new AV.Query(className);
        for (var key in option) {
            query.equalTo(key, option[key]);
        }
        query.find().then((res) => {
            reslove(res);
        }, (err) => {
            reject(err);
        })
    });
}

const updateObject = (object, className) => {
    return new Promise((reslove, reject) => {
        if (object.objectId) {
            var obj = AV.Object.createWithoutData(className, object.objectId);
            delete object.objectId;
            obj.set(object).save().then((res) => {
                reslove(res);
            }, (err) => {
                reject(err);
            })
        } else {
            reject(new Error('objectId 不能为空'))
        }
    });
}

const saveObject = (object, className) => {
    return new Promise((reslove, reject) => {
        var _class = AV.Object.extend(className);
        var obj = new _class();
        obj.set(object).save().then((res) => {
            reslove(res);
        }, (err) => {
            reject(err);
        })
    });
}

module.exports = {
    queryTest,
    queryAll,
    saveObject,
    updateObject,
    queryVersion,
    queryOption,
    queryOptionPage
}
